import { Message } from 'ant-design-vue';
// 格式化时间
export function renderTime(date) {
  var dateee = new Date(date).toJSON();
  return new Date(+new Date(dateee) + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
}

// 格式化时间为年月日
export function renderTimeToYMD(dateTime) {
  var date = new Date(dateTime)
  return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日'
}

// 返回当前时间 例00:00:00
export function currTime(_Date) {
  const date = new Date(_Date)
  return `${date.getHours()}:${date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()}:${date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()}`
}

// 转换毫秒
export function toMs(date) {
  return new Date(date).getTime()
}

export function countDown(stratTime, endTime) {
  // 现在时间
  var now = new Date(stratTime);
  //截止时间
  var until = new Date(endTime);
  // 计算时会发生隐式转换，调用valueOf()方法，转化成时间戳的形式
  var days = (until - now) / 1000 / 3600 / 24;
  // 下面都是简单的数学计算 
  var day = Math.floor(days);
  var hours = (days - day) * 24;
  var hour = Math.floor(hours);
  var minutes = (hours - hour) * 60;
  var minute = Math.floor(minutes);
  var seconds = (minutes - Number(minute)) * 60;
  var second = Math.floor(seconds);
  return (day ? day + '天' : '') + hour + '小时' + (minute < 10 ? '0' + (minute) : minute) + '分钟' + (second < 10 ? '0' + (second) : second) + '秒';
}

/**
 * @desc 防抖函数
 * @param {需要防抖的函数} func
 * @param {延迟时间} wait
 * @param {是否立即执行} immediate
 */
export function debounce(func, wait, immediate) {
  let timeout
  return function (...args) {
    let context = this
    if (timeout) clearTimeout(timeout)

    if (immediate) {
      let callNow = !timeout
      timeout = setTimeout(function () {
        timeout = null
      }, wait)
      if (callNow) func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait)
    }
  }
}


/**
 * 节流
 * @param {Function} func 要执行的回调函数 
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
let timer, flag;
export function throttle(func, wait = 200, immediate = true) {
  if (immediate) {
    if (!flag) {
      flag = true;
      // 如果是立即执行，则在wait毫秒内开始时执行
      typeof func === 'function' && func();
      timer = setTimeout(() => {
        flag = false;
      }, wait);
    }
  } else {
    if (!flag) {
      flag = true
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      timer = setTimeout(() => {
        flag = false
        typeof func === 'function' && func();
      }, wait);
    }

  }
}

// GUID
export function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0,
      v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

// 站点域名 判断是（开发环境、测试环境）还是生产环境 不同域名文件存放的路径都不同
export function location(window) {

  // if (window.location.host == 'codelover.club') return "https://codelover.club"
  // else if (window.location.host == 'www.codelover.club') return "https://www.codelover.club"
  // else if (window.location.host == 'demo.codelover.club') return "https://demo.codelover.club"
  // else if (window.location.host == 'demo.codelover.club') return "https://demo.codelover.club"
  // else if (window.location.host == '10.1.6.130') return "http://10.1.6.130"
  if (window.location.host == 'localhost:8080') return "http://10.1.6.130"
  return window.location.origin //"http://test.codelover.club" //http://localhost:8080
}

// 站点域名 判断是（开发环境、测试环境）还是生产环境 
// 题库正式环境8002 开发环境3103
export function location_QuestionBank(window) {
  // if (window.location.host == 'codelover.club' || window.location.host == 'www.codelover.club' || window.location.host == 'demo.codelover.club')
  //   return "https://" + window.location.host + "/qb"
  // else
  if (window.location.host == 'localhost:8080') return "http://10.1.6.130/qb"
   return  window.location.origin  + "/qb"  //"http://" + window.location.host +
}

//获取cookie
export function getCookie(cname) {
  var name = cname + '='
  var ca = document.cookie.split(';')
  for (var i = 0; i < ca.length; i++) {
    var c = ca[i]
    while (c.charAt(0) == ' ') c = c.substring(1)
    if (c.indexOf(name) != -1) return c.substring(name.length, c.length)
  }
  return null
}

//封装一个方法判断数组和对象
export function isType(obj) {
  var type = Object.prototype.toString.call(obj);
  if (type == '[object Array]') { return 'Array'; }
  else if (type == '[object Object]') { return "Object" }
  else { return 'param is no object type'; }
}

import { videoUpload } from '@/request/upload'
// 上传视频
export function VideoUpload(data) {
  return new Promise((resolve) => {
    videoUpload(data).then(res => {
      if (res) { resolve(res) } else resolve(false)
    }).catch(err => resolve(false))
  })
}

// 判断是不是JSON字符串
export function isJSONstr(str) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }
}

// JSON字符串的submitContent转为JSON对象
export function changeSubmitContentfomart(submitContentStr) {
  let submitContent = { data: null, isEncoded: false }
  // debugger
  if (isJSONstr(submitContentStr)) {
    submitContent = JSON.parse(submitContentStr)
    if (submitContent.isEncoded && submitContent.data) {
      submitContent.data = JSON.parse(decodeURIComponent(submitContent.data))
    }
  }
  // debugger
  if (typeof submitContentStr === 'object') return submitContentStr
  return Object.assign(submitContent, submitContentStr)
}

// 点击展示的内容
export function handelItem(node, item, that, isFindIndex) {
  if (!item.type) {
    item.type =
      item.fileName.substring(item.fileName.lastIndexOf(".") + 1) ||
      item.fileUrl.substring(item.fileUrl.lastIndexOf(".") + 1);
  }
  if (["docx", "xlsx", "pdf", "pptx", "mp4", "m3u8", "png", "jpg", "jpeg", "gif", "bmp", "DOCX", "XLSX", "PDF", "PPTX", "PNG", "JPG", "JPEG", "GIF",].indexOf(item.type) !== -1) {
    that.amplifyFile = item;
    that.amplify = true;
  } else if (["zip", "rar", "ZIP", "RAR"].indexOf(item.type) !== -1) {
    // 是压缩文件 并且还未压缩 就解压
    if (!item.subFiles || !item.subFiles.length) {
      // let findIndex = null;
      // if (isFindIndex) {
      //   findIndex = that.fileList.findIndex(
      //     (fitem) => fitem.$treeNodeId == node.data.$treeNodeId
      //   );
      // }
      // that.handleDecompression(node, item, findIndex);
    } else {
      if (isFindIndex) return
      that.$nextTick(() => {
        node.expanded = !node.expanded;
      });
    }
    return;
  } else {
    // 无法预览的文件直接下载
    window.open(item.fileUrl);
    return;
  }
}

// 复制
export function copy(string) {
  var textarea = document.getElementById("copyText");
  textarea.value = string
  textarea.select();
  let a = document.execCommand("Copy", false);
  if (a) Message.success({ content: '已复制' })
}

/**
 * https://developer.mozilla.org/zh-CN/docs/Web/API/Navigator/clipboard
 * 获取剪切板数据
 * */
export const getClipboard = async () => {
  // navigator clipboard 需要https等安全上下文
  if (navigator.clipboard && window.isSecureContext) {
    return await navigator.clipboard.readText().then(clipText => {
      return clipText
    });
  } else return null
}

//插入 
//为字符串插入字符 其中soure为原字符串,start为将要插入字符的位置，newStr为要插入的字符
export function insertStr(soure, start, newStr) {
  return soure.slice(0, start) + newStr + soure.slice(start);
}

export default {
  renderTime,
  renderTimeToYMD,
  guid,
  throttle,
  location,
  location_QuestionBank,
  getCookie,
  currTime,
  toMs,
  isType,
  VideoUpload,
  isJSONstr,
  changeSubmitContentfomart,
  countDown,
  handelItem,
  copy,
  insertStr,
  getClipboard
}